package me.linczh.framework.filter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import me.linczh.framework.action.ActionItem;
import me.linczh.framework.action.ActionMapping;

public class ActionDispatcherFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		System.out.println("ActionFilter#doFilter");
		String requestURL = ((HttpServletRequest)request).getRequestURI();
		System.out.println(requestURL);
		requestURL = requestURL.toLowerCase();
		if (requestURL.endsWith(".action")) {
			ActionMapping mapping = ActionMapping.getInstance();
			ActionItem item = mapping.getActionItem((HttpServletRequest)request);
			String actionClass = item.getActionClass();
			try {
				Class<?> executeClass = Class.forName(actionClass);
				Method method = executeClass.getMethod("execute", ServletRequest.class, ServletResponse.class, ActionItem.class);
				Object[] args = {request, response, item};
				method.invoke(executeClass.newInstance(), args);
				//executor.execute(request, response, item);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
